package io.gitee.wiqer.simple;

import java.util.Stack;

public class SolutionNC52_IsValid {
    /**
     *
     * @param s string字符串
     * @return bool布尔型
     */
    public boolean isValid (String s) {

        if (s == null || s.length() == 0) {
            return false;
        }

        Stack<Character> stack = new Stack<>();

        char[] chars = s.toCharArray();

        for (int i = 0; i < chars.length; i++) {

            if ('(' == chars[i]) {
                stack.push(')');
            } else if ('[' == chars[i]) {
                stack.push(']');
            } else if ('{' == chars[i]) {
                stack.push('}');
            } else {
                /**
                 * 无法配对
                 */
                if (stack.isEmpty() ){
                    return false;
                }
                //配对失败
                else if(stack.pop() != chars[i]) {
                    return false;
                }
            }
        }

        //最后可能栈里还有元素 代表非合法括号序列
        return stack.isEmpty();
    }
}
